from alipay import AliPay,AliPayConfig
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.orders.models import OrderInfo
from apps.pay.models import Payment
from meiduo_mall import settings
from utils.views import LoginRequiredJSONMixin


class PaymentView(LoginRequiredJSONMixin, View):
    def get(self,request,order_id):
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'wu ci ding dan'})
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG,  # 默认False
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        subject = "美多商城测试订单"
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),  # 一定要进行类型转换,因为decimal不是基本数据类型
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功之后,跳转的页面
            notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        # 7. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'alipay_url': pay_url})

class PaymentStatusView(View):
    def put(self,request):
        data=request.GET
        data=data.dict()
        signature = data.pop("sign")
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG,  # 默认False
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        # verification
        success = alipay.verify(data, signature)
        if success :
            trade_no=data.get('trade_no')
            order_id=data.get('out_trade_no')
            Payment.objects.create(
                trade_id=trade_no,
                order_id=order_id,
            )
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return JsonResponse({'code':0,'errmsg':'ok','trade_id':trade_no})
        else:
            return  JsonResponse({'code':400,'errmsg':'zhuangtai biangeng fail'})

"""
商家账号qtbkso1353@sandbox.com
商户UID2088621955532541
登录密码111111

买家账号wsjktj2827@sandbox.com
登录密码111111
支付密码111111
用户名称wsjktj2827
证件类型身份证(IDENTITY_CARD)
证件号码392037199008182244
"""
